import datetime
import json
from decimal import Decimal

from django.core import serializers
from django.http import JsonResponse


from django.core import serializers
from django.http import JsonResponse
from unicodedata import decimal

import CoreSubSystem
from CoreSubSystem.models import user
from UserSubSystem.models import card, rechargeRecord, transactionRecord, myHolding, asset, profitDetail, fundPlan


# 介绍返回数据方法的实现步骤，下同
def get_all_cards(request):
    '''
        根据用户id返回用户信用卡列表
    :param request: get形式的request，包括了user_id
    :return: 列表形式的用户信用卡对象
    '''
    # 从get方法中取得用户id
    id = request.GET.get("user_id")
    # 在数据库中查找该用户的所有银行卡对象
    finded_card = card.objects.filter(user_id=id)
    # 根据查询集数量确定flag
    flag = False
    data = {'data': '', 'flag': flag}
    if len(finded_card) > 0:
        flag = True
        # queryset转list[object]
        return_object = list(finded_card)
        # json序列化
        return_json = serializers.serialize("json", return_object)
        # 添加到字典，键是‘data’，值是list[object]，同时添加flag
        data['data'] = return_json
        data['flag'] = flag
    # 返回json字符串
    return JsonResponse(data)


def get_all_recharge_records(request):
    '''
        根据用户id返回充值记录对象列表
        :param request: get形式的request，包括了user_id
        :return: 列表形式的充值记录对象列表
    '''
    id = request.GET.get("user_id")
    finded_recharge_record = rechargeRecord.objects.filter(user_id=id)
    flag = False
    data = {'data': '', 'flag': flag}
    if len(finded_recharge_record) > 0:
        flag = True
        return_object = list(finded_recharge_record)
        return_json = serializers.serialize("json", return_object)
        data['data'] = return_json
        data['flag'] = flag
    return JsonResponse(data)


def get_all_transaction_records(request):
    '''
        根据用户id返回交易记录对象列表
        :param request: get形式的request，包括了user_id
        :return: 列表形式的交易记录对象列表
    '''
    id = request.GET.get("user_id")
    finded_transaction_record = transactionRecord.objects.filter(user_id=id)
    flag = False
    data = {'data': '', 'flag': flag}
    if len(finded_transaction_record) > 0:
        flag = True
        return_object = list(finded_transaction_record)
        return_json = serializers.serialize("json", return_object)
        data['data'] = return_json
        data['flag'] = flag
    return JsonResponse(data)


def get_all_assets(request):
    '''
        根据用户id返回资产对象列表
        :param request: get形式的request，包括了user_id
        :return: 列表形式的资产对象列表
    '''
    id = request.GET.get("user_id")
    finded_assets = asset.objects.filter(user_id=id)
    flag = False
    data = {'data': '', 'flag': flag}
    if len(finded_assets) > 0:
        flag = True
        return_object = list(finded_assets)
        return_json = serializers.serialize("json", return_object)
        data['data'] = return_json
        data['flag'] = flag
    return JsonResponse(data)


# 注意此方法较为特殊，不是直接将queryset转为list，而是包装一个新对象hold再添加到list
def get_all_my_holding(request):
    '''
        根据用户id返回我的持有对象列表
        :param request: get形式的request，包括了user_id
        :return: 列表形式的我的持有对象列表
    '''
    id = request.GET.get("user_id")
    finded_my_holding = myHolding.objects.filter(user_id=id)
    flag = False
    data = {'data': '', 'flag': flag}
    if len(finded_my_holding) > 0:
        flag = True
        list = []
        for item in finded_my_holding:
            fund = item.fund_id

            hold = {
                'id': item.id,
                'fund_name': fund.fund_name,
                'fund_amount': item.fund_amount,
                'yesterday_profit': item.yesterday_profit,
                'holding_profit': item.holding_profit,
                'holding_profit_rate': (item.holding_profit / item.fund_amount * 100).quantize(Decimal("0.00")),
                'user_id': id,
                # 如果写item.fund_id，则值会变成对象
                'fund_id': fund.id
                #     将来可能绑定更多fund的字段用于展示
                #     xxx :fund.xxx
                #     xxx :fund.xxx
                #     xxx :fund.xxx
            }
            list.append(hold)
        return_json = list
        data['data'] = return_json
        data['flag'] = flag
    return JsonResponse(data)


def get_all_my_profit_details(request):
    '''
        根据用户id返回收益明细列表
        :param request: get形式的request，包括了user_id
        :return: 列表形式的收益明细列表
    '''
    id = request.GET.get("user_id")
    finded_profit_detail = profitDetail.objects.filter(user_id=id)
    flag = False
    data = {'data': '', 'flag': flag}
    if len(finded_profit_detail) > 0:
        flag = True
        return_object = list(finded_profit_detail)
        return_json = serializers.serialize("json", return_object)
        data['data'] = return_json
        data['flag'] = flag
    return JsonResponse(data)

def get_all_fund_plans(request):
    user_id = request.GET.get("user_id")
    all_this_user_fund_plan = fundPlan.objects.filter(user_id=user_id).all()
    return_fund_plans = []
    for each_fund_plan in all_this_user_fund_plan:
        fund_name = each_fund_plan.fund_id.fund_name
        fund_proportion = each_fund_plan.fund_proportion
        fund_type = each_fund_plan.fund_id.fund_type
        return_fund_plans.append({"fund_name":fund_name,"fund_proportion":fund_proportion,"fund_type":fund_type})
    return JsonResponse({"flag":True,"data":return_fund_plans})

def pay_verify(request):
    operate_type = request.POST.get("operate_type")
    transaction_amount = Decimal(float(request.POST.get("transaction_amount")))
    transaction_source = request.POST.get("transaction_source")
    user_id = request.POST.get("user_id")
    buy_password = request.POST.get("buy_password")
    flag = False
    return_msg = "failed"
    if operate_type == "buy":
        if transaction_source == '1':
            try:
                finded_user = user.objects.filter(user_password=buy_password).get(id=user_id)
                if transaction_amount <= finded_user.user_wallet_balance:
                    finded_user.user_wallet_balance -= transaction_amount
                    finded_user.save()
                    flag = True
                    transaction_record = transactionRecord()
                    transaction_record.operate_type = transactionRecord.CHANGE_INTO
                    transaction_record.transaction_amount = transaction_amount
                    transaction_record.operate_time = datetime.datetime.now()
                    transaction_record.operate_state = "已完成"
                    transaction_record.operate_finish_time = datetime.datetime.now()
                    transaction_record.user_id_id = user_id
                    transaction_record.transaction_source = "余额"
                    transaction_record.save()
                    # myHolding.objects.filter(user_id_id=user_id).all().delete()
                    funds_belong_to_user = fundPlan.objects.filter(user_id_id=user_id).all()
                    for each_fund in funds_belong_to_user:
                        each_my_holding = myHolding()
                        each_my_holding.fund_id = each_fund.fund_id
                        each_my_holding.fund_amount = each_fund.fund_proportion * transaction_amount
                        each_my_holding.user_id_id = user_id
                        each_my_holding.holding_profit = 0
                        each_my_holding.yesterday_profit = 0
                        each_my_holding.save()
                    return_msg = "成功支付!"
                else:
                    return_msg = "此用户账户的余额不足!"
            except Exception as e:
                print(e)
                return_msg = "支付密码错误!"
        else:
            try:
                user_card = card.objects.filter(user_id_id=user_id).filter(card_password=buy_password).get(card_number=transaction_source)
                if transaction_amount <= user_card.card_balance:
                    user_card.card_balance -= transaction_amount
                    user_card.save()
                    flag = True

                    transaction_record = transactionRecord()
                    transaction_record.operate_type = transactionRecord.CHANGE_INTO
                    transaction_record.transaction_amount = transaction_amount
                    transaction_record.operate_time = datetime.datetime.now()
                    transaction_record.operate_state = "已完成"
                    transaction_record.operate_finish_time = datetime.datetime.now()
                    transaction_record.user_id_id = user_id
                    transaction_record.transaction_source = user_card.card_bank
                    transaction_record.save()

                    funds_belong_to_user = fundPlan.objects.filter(user_id_id=user_id).all()
                    for each_fund in funds_belong_to_user:
                        each_my_holding = myHolding()
                        each_my_holding.fund_id = each_fund.fund_id
                        each_my_holding.fund_amount = each_fund.fund_proportion * transaction_amount
                        each_my_holding.user_id_id = user_id
                        each_my_holding.holding_profit = 0
                        each_my_holding.yesterday_profit = 0
                        each_my_holding.save()
                    return_msg = "成功支付!"
                else:
                    return_msg = "此银行卡的余额不足!"
            except Exception as e:
                print(e)
                return_msg = "支付密码错误!"

        return JsonResponse({"flag":flag,"data":return_msg})

def sell_verify(request):
    print(request.POST)
    operate_type = request.POST.get("operate_type")
    transaction_amount = Decimal(float(request.POST.get("transaction_amount")) * 0.01 )
    transaction_source = request.POST.get("transaction_source")
    user_id = request.POST.get("user_id")
    sell_password = request.POST.get("sell_password")
    flag = False
    return_msg = "转出失败!"
    if operate_type == "sell":
        if transaction_source == '1':
            try:
                finded_user = user.objects.filter(user_password=sell_password).get(id=user_id)
                my_holdings_to_user = myHolding.objects.filter(user_id_id=user_id).all()
                total_gain_money = 0
                for my_holding in my_holdings_to_user:
                    each_gain_money = my_holding.fund_amount * transaction_amount
                    total_gain_money += each_gain_money
                    my_holding.fund_amount -= each_gain_money
                    my_holding.save()
                finded_user.user_wallet_balance += total_gain_money
                finded_user.save()
                flag = True
                transaction_record = transactionRecord()
                transaction_record.operate_type = transactionRecord.TRANSFER_OUT
                transaction_record.transaction_amount = total_gain_money
                transaction_record.operate_time = datetime.datetime.now()
                transaction_record.operate_state = "已完成"
                transaction_record.operate_finish_time = datetime.datetime.now()
                transaction_record.user_id_id = user_id
                transaction_record.transaction_source = "余额"
                transaction_record.save()
                return_msg = "成功转出!"
            except Exception as e:
                print(e)
                return_msg = "转出密码错误!"
        else:
            try:
                my_holdings_to_user = myHolding.objects.filter(user_id_id=user_id).all()
                total_gain_money = 0
                for my_holding in my_holdings_to_user:
                    each_gain_money = my_holding.fund_amount * transaction_amount
                    total_gain_money += each_gain_money
                    my_holding.fund_amount -= each_gain_money
                    my_holding.save()
                user_card = card.objects.filter(user_id_id=user_id).filter(card_password=sell_password).get(
                    card_number=transaction_source)
                user_card.card_balance += total_gain_money
                user_card.save()
                transaction_record = transactionRecord()
                transaction_record.operate_type = transactionRecord.TRANSFER_OUT
                transaction_record.transaction_amount = total_gain_money
                transaction_record.operate_time = datetime.datetime.now()
                transaction_record.operate_state = "已完成"
                transaction_record.operate_finish_time = datetime.datetime.now()
                transaction_record.user_id_id = user_id
                transaction_record.transaction_source = user_card.card_bank
                transaction_record.save()
                flag = True
                return_msg = "成功转出!"
            except Exception as e:
                print(e)
                return_msg = "转出密码错误!"

        return JsonResponse({"flag": flag, "data": return_msg})